<template>
  <div class="ygseyt">
    <h1>权限管理</h1>

    <!-- 数据列表（新增职位） -->
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <!-- <el-button size="mini" class="btn-add" @click="addzw" style="float:right">新增权限</el-button> -->
    </el-card>
    <!-- 表格数据 -->
    <div class="table-container">
      <el-table :data="currentData" border style="width: 100%" highlight-current-row>
        <el-table-column prop="name" label="权限名称"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column prop="createBy" label="创建人"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" :formatter="dateFormatter"></el-table-column>
        <el-table-column prop="updateBy" label="更新人"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" :formatter="dateFormatter2"></el-table-column>
        <el-table-column label="操作" width="160px">
          <!-- 通过 Scoped slot 可以获取到 row, column, $index 和 store（table 内部的状态管理）的数据 -->
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <!-- <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="block">
      <el-pagination
        background
        hide-on-single-page
        layout="prev, pager, next"
        :total="pageNum"
        :page-size="xuanyan.pageSize"
        :pager-count="xuanyan.pageCount"
        @current-change="changePage"
        :current-page="xuanyan.currentPage"
      ></el-pagination>
    </div>
    <!-- 编辑Dialog -->
    <el-dialog
      title="编辑权限"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      placeholder="aaa"
    >
      <el-form
        :model="bjQxFrom"
        :rules="rules"
        ref="bjQxFrom"
        label-width="100px"
        class="demo-bjQxFrom"
      >
        <el-form-item label="职位：" prop="name">
          <el-input v-model="bjQxFrom.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="bjQxFrom.remark"></el-input>
        </el-form-item>
        <el-form-item label="权限菜单：" prop="remark" v-show="show">
          <el-checkbox-group v-model="checkList">
            <el-checkbox label="菜品管理"></el-checkbox>
            <el-checkbox label="运营管理"></el-checkbox>
            <el-checkbox label="库存管理"></el-checkbox>
            <el-checkbox label="信息管理" :disabled="disa"></el-checkbox>
            <el-checkbox label="财务分析"></el-checkbox>
            <el-checkbox label="系统设置" disabled></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="修改人：" prop="updateBy">
          <el-input v-model="bjQxFrom.updateBy" disabled></el-input>
        </el-form-item>
        <el-form-item label="修改时间：" prop="updateTime">
          <el-input v-model="bjQxFrom.updateTime" disabled></el-input>
        </el-form-item>

        <el-form-item>
          <!-- <el-button @click="resetForm('bjQxFrom')">重 置</el-button> -->
          <el-button type="primary" @click="submitForm('bjQxFrom')">确定修改</el-button>
          <el-button @click="closeDao">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 新增Dialog -->
    <el-dialog
      title="新增权限"
      :visible.sync="dialogVisible2"
      width="30%"
      :before-close="handleClose"
      placeholder="aaa"
    >
      <el-form
        :model="xzQxFrom"
        :rules="bjRules"
        ref="xzQxFrom"
        label-width="100px"
        class="demo-xzQxFrom"
      >
        <el-form-item label="权限名称：" prop="name">
          <el-input v-model="xzQxFrom.name"></el-input>
        </el-form-item>
        <el-form-item label="权限菜单：" prop="remark">
          <el-checkbox-group v-model="checkList">
            <el-checkbox label="菜品管理"></el-checkbox>
            <el-checkbox label="运营管理"></el-checkbox>
            <el-checkbox label="库存管理"></el-checkbox>
            <el-checkbox label="信息管理"></el-checkbox>
            <el-checkbox label="财务分析管理"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input type="textarea" v-model="xzQxFrom.remark" placeholder="请输入备注信息"></el-input>
        </el-form-item>
        <el-form-item label="创建人：" prop="createBy">
          <el-input v-model="xzQxFrom.createBy" disabled></el-input>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-input v-model="xzQxFrom.createTime" disabled></el-input>
        </el-form-item>

        <el-form-item>
          <el-button @click="resetForm('xzQxFrom')">重 置</el-button>
          <el-button type="primary" @click="submitxzForm2('xzQxFrom')">确认添加</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDao">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters, mapActions, mapState } from "vuex";
import axios from "../../http/http";
import * as url from "../../http/api";
export default {
  name: "ygSet",
  data() {
    return {
      show: false,
      disa: true,
      checkList: [],
      // -------------------编辑权限
      // Dialog对话框
      dialogVisible: false,
      bjQxFrom: {
        id: "",
        name: "",
        remark: "",
        updateBy: "",
        updateTime: ""
      },
      rules: {
        jobName: [
          { required: false, message: "请输入职位名称", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" }
        ]
      },
      // -------------------新增权限
      dialogVisible2: false,
      xzQxFrom: {
        name: "",
        remark: "",
        createBy: "",
        createTime: ""
      },
      bjRules: {
        name: [
          { required: true, message: "请输入权限名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 5 个字符", trigger: "blur" }
        ],
        remark: [
          { required: true, message: "请输入备注信息", trigger: "blur" },
          { min: 2, max: 60, message: "长度在 2 到 60 个字符", trigger: "blur" }
        ]
      },
      // 表格渲染及分页
      xuanyan: {
        currentPage: 1, //当前页
        pageSize: 8, //显示数据条数
        pageCount: 7 //页码最大显示数
      }
    };
  },
  computed: {
    // 渲染表格数据
    // ...mapState({
    //   qxlist:function(state){
    //     return state.hpStore.qxlist
    //   }
    // }),
    currentData() {
      let start = (this.xuanyan.currentPage - 1) * this.xuanyan.pageSize;
      let end = this.xuanyan.currentPage * this.xuanyan.pageSize;
      return this.$store.state.hpStore.qxlist.slice(start, end);
    },
    pageNum() {
      return this.$store.state.hpStore.qxlist.length;
    }
  },
  // -------------------------------------------------------------------------------------------------
  methods: {
    ...mapGetters(["getUserName"]),
    // 获取日期
    CurentTime() {
      var now = new Date();
      var year = now.getFullYear(); //年
      var month = now.getMonth() + 1; //月
      var day = now.getDate(); //日
      // var hh = now.getHours(); //时
      // var mm = now.getMinutes(); //分
      // var ss = now.getSeconds(); //秒
      var clock = year + "-";
      if (month < 10) clock += "0";
      clock += month + "-";
      if (day < 10) clock += "0";
      clock += day;
      // if (hh < 10) clock += "0";
      // clock += hh + ":";
      // if (mm < 10) clock += "0";
      // clock += mm + ":";
      // if (ss < 10) clock += "0";
      // clock += ss;
      return clock;
    },
    // -----------------------------------------------删除
    // 删除权限 完成
    handleDelete(index, row) {
      this.$confirm("删除后不可恢复, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let obj = {
            id: row.id
          };
          // console.log(obj)
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // ------------------------------------------------编辑(缺少接口)
    // 得到要获取的权限name
    getQxName(name) {
      this.checkList = [];
      for (let key in this.$getSession(name)) {
        if (this.$getSession(name)[key] == true) {
          // console.log(key);
          // console.log(this.$getSession(name)[key]);
          switch (key) {
            case "setCp":
              this.checkList.push("菜品管理");
              break;
            case "setYy":
              this.checkList.push("运营管理");
              break;
            case "setKc":
              this.checkList.push("库存管理");
              break;
            case "setJc":
              this.checkList.push("信息管理");
              break;
            case "setCw":
              this.checkList.push("财务分析");
              break;
            case "setXt":
              this.checkList.push("系统设置");
              break;
          }
        }
      }
    },
    handleEdit(index, row) {
      // console.log(row.id)
      row.id == 1 ? (this.show = false) : (this.show = true);
      this.dialogVisible = true;
      // console.log(this.show)
      row.id == 4 ? (this.disa = true) : (this.disa = false);
      // this.bjQxFrom = row;
      for (let key in this.currentData[index]) {
        if (this.bjQxFrom[key] != undefined) {
          this.bjQxFrom[key] = this.currentData[index][key];
        }
      }
      this.bjQxFrom.updateTime = this.CurentTime();
      this.bjQxFrom.updateBy = this.getUserName();
      switch (row.id) {
        case 2:
          this.getQxName("account");
          break;
        case 3:
          this.getQxName("admin");
          break;
        case 4:
          this.getQxName("sAdmin");
          break;
      }
      // console.log(this.bjQxFrom)
    },
    // 编辑提交事件(缺少请求接口)
    submitForm(formName) {
      let obj = {};
      Object.assign(obj, this.bjQxFrom);
      // console.log(obj.id);
      let name = "";
      let cd = {
        setCp: false,
        setYy: false,
        setKc: false,
        setJc: false,
        setXt: false,
        setCw: false
      };
      switch (obj.id) {
        case 2:
          name = "account";
          break;
        case 3:
          name = "admin";
          break;
        case 4:
          name = "sAdmin";
          break;
      }
      // console.log(this.checkList)
      this.checkList.forEach(item => {
        // console.log(item)
        switch (item) {
          case "菜品管理":
            cd.setCp = true;
            break;
          case "运营管理":
            cd.setYy = true;
            break;
          case "库存管理":
            cd.setKc = true;
            break;
          case "系统设置":
            cd.setXt = true;
            break;
          case "信息管理":
            cd.setJc = true;
            break;
          case "财务分析":
            cd.setCw = true;
            break;
        }
      });
      this.$refs[formName].validate(valid => {
        if (valid) {
          axios({
            url: "/mgrsite/SAdmin/updatePower",
            method: "post",
            data: obj
          }).then(res => {
            // console.log(res);
            if (res.data.status == "success") {
              this.$setSession(name, cd);
              this.bjQxAct(name);
              this.closeDao();
              this.qxData();
              this.$message({
                type: "success",
                message: "修改成功!"
              });
            }
          });
          // console.log(obj)
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // -------------------------------------------------添加(需要提交请求接口)
    addzw() {
      this.dialogVisible2 = true;
      this.xzQxFrom.createBy = this.getUserName();
      this.xzQxFrom.createTime = this.CurentTime();
    },
    // 新增提交事件(缺少请求接口)
    submitxzForm2(formName) {
      let obj = {};
      Object.assign(obj, this.xzQxFrom);
      console.log(this.checkList);
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.checkList.length == 0) {
            this.$message({
              type: "warring",
              message: "请选择权限"
            });
          } else {
            console.log(obj);
          }
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },
    // ----------------------------------------------------本页面公共方法
    // 更改页码
    changePage(val) {
      this.xuanyan.currentPage = val;
    },
    // 关闭Diolog 方式一
    closeDao() {
      this.dialogVisible = false;
      this.dialogVisible2 = false;
      this.checkList = [];
      this.bjQxFrom = {
        id: "",
        name: "",
        remark: "",
        updateBy: "",
        updateTime: ""
      };
    },
    // 关闭Dialog 方式二
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
          this.checkList = [];
          this.bjQxFrom = {
            id: "",
            name: "",
            remark: "",
            updateBy: "",
            updateTime: ""
          };
        })
        .catch(_ => {});
    },
    // 编辑重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    dateFormatter(row, column) {
      let datetime = row.createTime;
      if (datetime) {
        datetime = new Date(datetime);
        let y = datetime.getFullYear() + "-";
        let mon = datetime.getMonth() + 1 + "-";
        let d = datetime.getDate();
        return y + mon + d;
      }
      return "";
    },
    dateFormatter2(row, column) {
      let datetime = row.updateTime;
      if (datetime) {
        datetime = new Date(datetime);
        let y = datetime.getFullYear() + "-";
        let mon = datetime.getMonth() + 1 + "-";
        let d = datetime.getDate();
        return y + mon + d;
      }
      return "";
    },
    ...mapActions(["qxData", "bjQxAct"])
  },
  created() {
    this.qxData();
  }
};
</script>

<style scoped lang="less">
.operate-container {
  margin: 15px 0;
}
.block {
  position: absolute;
  left: 50%;
  bottom: 0%;
}
</style>